{extend name="layout/base" /}
{block name="title"}我的购物车 - {mall:config name="mall.sitename"/}{__block__}{/block}
{block name="meta"}
{__block__}
<link href="__ADDON__/__STYLE__/css/cart.css" rel="stylesheet">
<link href="__CDN__/assets/libs/bootstrap-table/dist/bootstrap-table.min.css" rel="stylesheet">
<link href="__ADDON__/__STYLE__/js/bt-ext/bt-group-by.css" rel="stylesheet">
{/block}

{block name="body"}
<body class="shopping_cart_page">
{/block}

{block name="main"}
<div class="container">
	<div id="stepflex" class="stepflex">
       <dl class="first doing">
          <dt class="s-num">1</dt>
          <dd class="s-text">我的购物车</dd>
          <dd></dd>
       </dl>
       <dl class="normal doing">
          <dt class="s-num">2</dt>
          <dd class="s-text">填写核对订单信息</dd>
       </dl>
       <dl class="last">
          <dt class="s-num1">3</dt>
          <dd class="s-text1">成功提交订单</dd>
       </dl>
    </div>
    <div class='mall-clear'></div>

    <div class='main-head'>填写并核对订单</div>
    <input type='hidden' class='j-ipt' id='c-s_addressId' value='{if isset($userAddress["id"]) }{$userAddress["id"]}{/if}'/>
    <input type='hidden' class='j-ipt' id='c-s_areaId' value='{if isset($userAddress["id"]) }{$userAddress["areaId2"]}{/if}'/>
    <!-- 送货方式 -->
    <div class='address-box'>
        <div class='box-head'>送货方式</div>
        <div class="mall-list-box">
            <div class="mall-frame2 j-selected" onclick="javascript:changeDeliverType(0,'deliverType',this)">快递运输<i></i></div>
            <div class="mall-frame2" onclick="javascript:changeDeliverType(1,'deliverType',this)">自提<i></i></div>
            <input type='hidden' value='0' id='c-deliverType' class='j-ipt' />
            <div class='mall-clear'></div>
        </div>
    </div>
    <!-- 用户地址 -->
    <div class='pay-box'>
       <div class='box-head'>收货人信息
           <a onclick="javascript:addAddress('{:empty($userAddress) ? \'add\' : \'index\'}');" class="btn btn-success btn-add add-addr">{:empty($userAddress) ? '添加' : '管理'}收货地址</a>
       </div>
       <!-- 选中地址 -->
       <div class='j-show-box {if empty($userAddress)}hide{/if}' >
          <div id="s_userName" class="mall-frame1 j-selected">{if isset($userAddress["id"]) }{$userAddress['name']}{/if}<i></i></div>
          <div class="address">
	          <span id='s_address'>
	          {if isset($userAddress["id"]) }
	          {$userAddress['name']}&nbsp;&nbsp;&nbsp;{$userAddress['areaName']}&nbsp;&nbsp;{$userAddress['address']}&nbsp;&nbsp;{$userAddress['phone']}
	          {/if}
	          </span>
	          &nbsp;&nbsp;
	          <span id="isdefault" {if(isset($userAddress['isDefault'])&&($userAddress['isDefault']==1))} class="j-default">默认地址{else /} >{/if}</span>
          </div>
          <div class='mall-clear'></div>
          <div class="address">
                <a class="mall-lfloat" href='javascript:void(0)' onclick='javascript:showAddressBox()' style=''>更换地址</a>
          </div>

       </div>
       <!-- 地址列表  -->
       <ul class='j-list-box' id='addressList'></ul>

    </div>
    <!-- 支付方式 -->
    <div class='pay-box'>
       <div class='box-head'>支付方式</div>
       <div class="mall-list-box">
          <div class="mall-frame2" onclick="javascript:changeSelected(0,'payType',this)">货到付款<i></i></div>
          <div class="mall-frame2 j-selected" onclick="javascript:changeSelected(1,'payType',this)">在线支付<i></i></div>
          <input type='hidden' value="1" id='c-payType' class='j-ipt' />
          <div class='mall-clear'></div>
       </div>
    </div>
    <!-- 商品清单 -->
    <div class='cart-box2'>
       <div class='box-head2'>商品清单</div>
        <table id="table"
               data-url="/addons/mall/order/getOrderMoney"
               data-group-by="true"
               data-group-by-field="name"
               data-group-by-sum-field="shoptotal"
               data-group-by-total-field="carttotal">
            <thead>
            <tr>
                <th data-field="goodsimg" data-formatter="imageFormatter" >图片</th>
                <th data-field="goodsname" data-formatter="goodsnameFormatter">名称与规格</th>
                <th data-field="shopprice" data-align="right" data-valign="middle">价格</th>
                <th data-field="goodsstock" data-align="right" data-valign="middle">库存</th>
                <th data-field="num" data-align="right" data-valign="middle">数量</th>
                <th data-field="total" data-align="right" data-valign="middle" >小计</th>
            </tr>
            </thead>
        </table>
        <div class='cart-footer'>
            <div class='cart-summary2'>
                <!-- 发票信息 -->
                <div class="pay-box">
                    <div class='box-head'>发票信息</div>
                    <div class="j-show-box">

                        <div style="float:left;" id="invoice_info">不开发票</div>
                        <div style="float:left;color:blue;margin-left:10px;cursor:pointer;" onclick='javascript:changeInvoice(1,"#invoiceClientDiv",this)'>修改</div>

                        <div class="mall-clear"></div>
                        <input type="hidden" id="c-invoice_obj" value="0" />
                        <input type="hidden" id="c-invoiceId" value="0" class='j-ipt' />
                        <input type='hidden' value='0' id='c-isInvoice' class='j-ipt' />
                        <input type='hidden' value='个人' id='c-invoiceClient' class='j-ipt' />
                    </div>
                </div>
            </div>
        </div>
    </div>

     <div class='cart-btn'>
        <a href='{:addon_url("mall/cart/index")}' class='mall-prev mall-cart-asha' style='width:105px;height:33px;line-height:33px;'>上一步</a>
        <a href='javascript:void(0)' onclick='javascript:addOrder()' class='mall-order mall-cart-reda' style='width:118px;height:33px;line-height:33px;'>提交订单</a>
        <div class='mall-clear'></div>
     </div>
</div>


<!-- 存储选中数据 -->
<div class='j-edit-box hide'>
    <form id='addressForm' autocomplete='off'>
        <input type='hidden' class='j-eipt' id='c-id' value=''/>
        <div class='rows'>
            <div class='label'>收货人<font color='red'>*</font>：</div>
            <div class='field'><input type='text' class='j-eipt' id='c-name' maxLength='25'/></div>
            <div class='mall-clear'></div>
        </div>
        <div class='rows'>
            <div class='label'>收货地址<font color='red'>*</font>：</div>
            <div class='field'>
                <input type='hidden' class='j-eipt' id='c-area_ids' style='width:300px' maxLength='200'/>
                <input type='text' class='j-eipt' id='c-area_ids_text' style='width:300px' maxLength='200'/>
                <input type='text' class='j-eipt' id='c-address' style='width:300px' maxLength='200'/>
            </div>
            <div class='mall-clear'></div>
        </div>
        <div class='rows'>
            <div class='label'>联系电话<font color='red'>*</font>：</div>
            <div class='field'><input type='text' id='c-phone' class='j-eipt' name="addrUserPhone" maxLength='50'/>  </div>
            <div class='mall-clear'></div>
        </div>
        <div class='rows'>
            <div class='label'>是否默认地址<font color='red'>*</font>：</div>
            <div class='radio-box'>
                <label style='margin-right:36px;'>
                    <input type='radio' name='isDefault' value='1' checked class='j-eipt mall-radio' id="isDefault1"/><label class="mt-1" for="isDefault1"></label>是
                </label>
                <label>
                    <input type='radio' name='isDefault' value='0' class='j-eipt mall-radio' id="isDefault2"/><label class="mt-1" for="isDefault2"></label>否
                </label>
            </div>
            <div class='mall-clear'></div>
        </div>
        <div class='rows'>
            <a href='javascript:void(0)' class='mall-cart-reda' id='saveAddressBtn' onclick='javascript:editAddress()' style='width:105px;line-height:33px;padding:6px 15px'>保存收货人地址</a>
        </div>
    </form>
</div>


{/block}

{block name="js"}
{__block__}
<script src="__CDN__/assets/libs/jquery/dist/jquery.min.js"></script>
<script src="__CDN__/assets/libs/bootstrap-table/dist/bootstrap-table.min.js"></script>
<script src="__CDN__/assets/libs/bootstrap-table/dist/bootstrap-table-locale-all.min.js"></script>
<script src="__ADDON__/__STYLE__/js/bt-ext/bt-group-by.js" ></script>
<script>
    var $table = $('#table')

    function initTable() {
        $table.bootstrapTable({
            locale: require.config.language,
            "groupByFormatter": function(value, row, index) {
                var html = [];
                html.push(value);
                if(row['shopQQ'] != ''){
                    html.push('<a href="tencent://message/?uin='+row['shopQQ']+'&Site=QQ交谈&Menu=yes">\n' +
                        '<img border="0" src="https://wpa.qq.com/pa?p=1:'+row['shopQQ']+':7" alt="QQ交谈" width="71" height="24" />\n' +
                        '</a>\n');
                }
                if(row['shopWangWang'] != '') {
                    html.push('<a target="_blank" href="https://www.taobao.com/webww/ww.php?ver=3&touid='+row['shopWangWang']+'&siteid=cntaobao&status=1&charset=utf-8">\n' +
                        '<img border="0" src="https://amos.alicdn.com/realonline.aw?v=2&uid='+row['shopWangWang']+'&site=cntaobao&s=1&charset=utf-8" alt="和我联系" />\n' +
                        '</a>\n');
                }
                html.push('订单备注：<input type="text" id="c-remark-'+row['shop_id']+'" data-shop-id="'+row['shop_id']+'" value="'+row['remark']+'" name="row[remarkshop]" class="j-ipt" style="width:420px" maxLength="100" placeholder="给卖家留言"/>');
                return html.join('');
            },
        });

    }

    /**
     * 计算订单金额
     */
    function getOrderMoney(){
        var params = {};
        params.isUseScore = $('#c-isUseScore').prop('checked')?1:0;
        params.useScore = $('#c-useScore').val();
        params.areaId2 = $('#c-s_areaId').val();
        //组装店铺留言为数组
        var remarkShop = [], remarkShopId = [], remarkArray = [];
        $('input[name="row[remarkshop]"]').each(function () {
            remarkShop.push($(this).val());
        });
        $('input[name="row[remarkshop]"]').each(function () {
             remarkShopId.push($(this).data("shop-id"));
        });
      if(remarkShop.length>1 && remarkShop.length===remarkShopId.length){
            remarkShop.forEach(function (item,index) {
                remarkArray[remarkShopId[index]] = item;
            })
        }else{
            remarkArray[remarkShopId] = remarkShop
        }
        params.memo = remarkArray;
        $.ajax({
            url: '/addons/mall/order/getOrderMoney',
            type: 'post',
            dataType: 'json',
            data: params,
            success: function (ret) {
                if(ret.length>0){
                    $table.bootstrapTable('load',ret);
                }
            },
        });
    }

    $(function() {
        initTable();

        $('#locale').change(initTable);

        if($('#c-s_areaId').val()>0) getOrderMoney();

    })

    /**
     *新增地址
     */
    function addAddress(act){
        Fast.api.open("/user/mall.user.address/"+act,act="add" ? '新增地址' : '管理地址', {
            callback: function(data) {
                getAddressList();
            }
        });
        return false;
    }

    /**
     *获取地址列表
     */
    function getAddressList(obj){
        var id = $('#c-s_addressId').val();
        $.ajax({
            url: '/user/mall/user/address/index',
            type: 'post',
            dataType: 'json',
            data: {rnd:Math.random()},
            success: function (ret) {
                if(ret.total>0){
                    if(ret.rows && ret.rows.length){
                        var list = ret.rows;
                        var html = [],tmp;
                        for(var i=0;i<list.length;i++){
                            tmp = list[i];
                            var selected = (id==tmp.id)?'j-selected':'';
                            html.push(
                                '<div class="mall-frame1 '+selected+'" onclick="javascript:changeAddrId('+tmp.id+')" id="addr-'+tmp.id+'" >'+tmp.name+'<i></i></div>',
                                '<li class="radio-box">',
                                tmp.name,
                                '&nbsp;&nbsp;',
                                tmp.area_ids_text+tmp.address,
                                '&nbsp;&nbsp;&nbsp;&nbsp;',
                                tmp.phone
                            )
                            if(tmp.isDefault==1){
                                html.push('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="j-default">默认地址</span>')
                            }
                            html.push('<div class="mall-clear"></div>','</li>');
                        }
                        html.push('<a style="color:#1c9eff" onclick="hideAddressBox()" href="javascript:;">选定地址</a>');
                        $('#addressList').html(html.join(''));
                    }else{
                        $('#addressList').empty();
                    }
                }else{
                    $('#addressList').empty();
                }
            },
        });

    }

    /**
     *显示更多地址
     */
    function showAddressBox(){
        getAddressList();
        //保留默认选项
        id = $('#c-s_addressId').val();
        inEffect($('#addr-'+id),1);
        $.ajax({
            url: '/user/mall/user/address/getById',
            type: 'post',
            dataType: 'json',
            data: {id:id},
            success: function (ret) {
                if(ret.code){
                    $('.j-list-box').show();
                    $('.j-show-box').hide();
                    setValues(ret.data);
                    $('input[name="addrUserPhone"]').val(ret.data.phone)
                }else{
                    if(ret.msg) Toastr.error(ret.msg);
                }
            },
        });
    }
    /**
     *选择收货地址
     */
    function changeAddrId(id){
        $.ajax({
            url: '/user/mall/user/address/getById',
            type: 'post',
            dataType: 'json',
            data: {id:id},
            success: function (ret) {
                if(ret.code){
                    inEffect($('#addr-'+id),1);
                    $('#c-s_addressId').val(ret.data.id);
                    setValues(ret.data);
                    // 设置收货地区市级id
                    $('#c-s_areaId').val(ret.data.areaId2);
                    // 计算运费
                    getOrderMoney();
                }else{
                    if(ret.msg) Toastr.error(ret.msg);
                }
            },
        });
    }

    /**
     *收起地址
     */
    function hideAddressBox(){
        var params = getParams('.j-eipt');
        $('#c-s_addressId').val(params.id);
        $('#c-s_areaId').val(params.areaId2);
        $('#s_userName').html(params.name+'<i></i>');
        $('#s_address').html(params.name+'&nbsp;&nbsp;&nbsp;'+params.area_ids_text+'&nbsp;&nbsp;'+params.address+'&nbsp;&nbsp;'+params.phone);
        if(params.isDefault==1){
            $('#isdefault').html('默认地址').addClass('j-default');
        }else{
            $('#isdefault').html('').removeClass('j-default');
        }

        $('.j-edit-box').hide();
        $('.j-list-box').hide();
        $('.j-show-box').show();
    }

    /**
     * 选择送货方式
     */
    function changeDeliverType(n,index,obj){
        changeSelected(n,index,obj);
        getOrderMoney();
    }


    var invoicebox;
    /**
     *修改开票信息
     */
    function changeInvoice(t,str,obj){
        var param = {};
        param.isInvoice = $('#c-isInvoice').val();
        param.invoiceId = $('#c-invoiceId').val();
        var loading = layer.load({msg:'正在请求数据，请稍后...'});
        $.post('/addons/mall/invoice/index',param,function(data){
            layer.close(loading);
            // layer弹出层
            invoicebox = layer.open({
                title:'发票信息',
                type: 1,
                area: ['628px', '420px'], //宽高
                content: data,
                success :function(){
                    if(param.invoiceId>0){
                        $('.inv_codebox').show();
                        $('#invoice_num').val($('#invoiceCode_'+param.invoiceId).val());
                    }
                },
            });
        });
    }

    function changeInvoiceItem(t,obj){
        $(obj).addClass('inv_li_curr').siblings().removeClass('inv_li_curr');
        $('.inv_editing').remove();// 删除正在编辑中的发票信息
        $('.inv_add').show();
        $('#c-invoiceId').val(t);
        if(t==0){
            // 为个人时，隐藏识别号
            $('.inv_codebox').css({display:'none'});
            $('#invoice_num').val(' ');
        }else{
            $('#invoice_num').val($('#invoiceCode_'+t).val());
            $('.inv_codebox').css({display:'block'});
        }
        $("#c-invoice_obj").val(t);
    }
    // 是否需要开发票
    function changeInvoiceItem1(t,obj){
        $(obj).addClass('inv_li_curr').siblings().removeClass('inv_li_curr');
        $('#c-isInvoice').val(t);
    }
    // 显示发票增加
    function invAdd(){
        $("#c-invoiceId").val(0);
        $("#c-invoice_obj").val(1);
        $('#invoice_num').val('');
        $('.inv_li').removeClass('inv_li_curr');// 移除当前选中样式
        $('.inv_ul').append('<li class="inv_li inv_li_curr inv_editing"><input type="text" id="invoiceHead" placeholder="新增单位发票抬头" value="" style="width:65%;height:21px;padding:1px;"><i></i><div style="top:8px;" class="inv_opabox"><a href="javascript:void(0)" onCLick="addInvoice()">保存</a></div></li>');
        $('.inv_ul').scrollTop($('.inv_ul')[0].scrollHeight);// 滚动到底部
        $('.inv_add').hide();// 隐藏新增按钮
        $('.inv_codebox').css({display:'block'});// 显示`纳税人识别号`
    }
    // 执行发票抬头新增
    function addInvoice(){
        var head = $('#invoiceHead').val();
        if(head.length==0){
            layer.msg('发票抬头不能为空');
            return;
        }
        var loading = Load({msg:'正在提交数据，请稍后...'});
        $.post('/addons/mall/Invoice/add',{invoiceHead:head},function(data){
            var json = toJson(data);
            layer.close(loading);
            if(json.status==1){
                $('#c-invoiceId').val(json.data.id);
                layer.msg(json.msg,{icon:1});
                $('.inv_editing').remove();
                var code = [];
                code.push('<li class=\'inv_li inv_li_curr\' onClick="changeInvoiceItem(\''+json.data.id+'\',this)">');
                code.push('<input type="text" value="'+head+'" readonly="readonly" class="invoice_input" id="invoiceHead_'+json.data.id+'" />');
                code.push('<input type="hidden" id="invoiceCode_'+json.data.id+'" value=""} /><i></i>');
                code.push('<div class="inv_opabox">');
                code.push('<a href=\'javascript:void(0)\' onClick="invEdit(\''+json.data.id+'\',this)" class="edit_btn">编辑</a>');
                code.push('<a href=\'javascript:void(0)\' onClick="editInvoice(\''+json.data.id+'\',this)" style="display:none;" class="save_btn">保存</a>');
                code.push('<a href=\'javascript:void(0)\' onClick="delInvoice(\''+json.data.id+'\',this)">删除</a></div></li>');
                $('.inv_li:first').after(code.join(''));
                // 显示新增按钮
                $('.inv_add').show();
            }else{
                layer.msg(json.msg,{icon:2});
            }
        });
    }
    // 显示发票修改
    function invEdit(id,obj){
        var input = $(obj).parent().parent().find('.invoice_input');
        input.removeAttr('readonly').focus();
        input.mouseup(function(){return false});
        $(obj).parent().parent().mouseup(function(){
            input.attr('readonly','readonly');
            $(obj).show().siblings('.save_btn').hide();
        });
        $(obj).hide().siblings('.save_btn').show();
        var invoice_code = $('#invoiceCode_'+id).val();
        $('.inv_codebox').css({display:'block'})
        $('#invoice_num').val(invoice_code);// 显示`纳税人识别号`)
    }
    // 完成发票修改
    function editInvoice(id,obj){
        var head = $('#invoiceHead_'+id).val();
        if(head.length==0){
            layer.msg('发票抬头不能为空');
            return;
        }
        var loading = Load({msg:'正在提交数据，请稍后...'});
        $.post('/addons/mall/Invoice/edit',{invoiceHead:head,id:id},function(data){
            var json = toJson(data);
            layer.close(loading);
            if(json.status==1){
                var input = $(obj).parent().parent().find('.invoice_input');
                input.attr('readonly','readonly')
                $(obj).hide().siblings('.edit_btn').show();
                layer.msg(json.msg,{icon:1});
            }else{
                layer.msg(json.msg,{icon:2});
            }
        });
    }
    // 设置页面显示值
    function setInvoiceText(invoiceHead){
        var isInvoice  = $('#c-isInvoice').val();
        var invoiceObj = $('#c-invoice_obj').val();// 发票对象
        var text = '不开发票';
        if(isInvoice==1){
            text = (invoiceObj==0)?'普通发票（纸质）  个人   明细':'普通发票（纸质）'+invoiceHead+' 明细';
        }
        $('#invoice_info').html(text);
        layer.close(invoicebox);

    }
    /**
     *保存纳税人识别号
     */
    function saveInvoice(){
        var isInv = $('#c-isInvoice').val();
        var num = $('#invoice_num').val();
        var id = $('#c-invoiceId').val();
        var invoiceHead = $('#invoiceHead').val();// 发票抬头
        var url = '/addons/mall/Invoice/add';
        var params = {};
        if(id>0){
            url = '/addons/mall/Invoice/edit';
            invoiceHead = $('#invoiceHead_'+id).val();// 发票抬头
            params.id = id;
        }
        params.invoiceHead = invoiceHead;
        params.invoiceCode = num;
        if($('#c-invoice_obj').val()!=0){
            $.ajax({
                url: url,
                type: 'post',
                dataType: 'json',
                data: {"row":params},
                success: function (ret) {
                    if(ret.code){
                        // 判断用户是否需要发票
                        setInvoiceText(invoiceHead);
                        if(id==0)$('#c-invoiceId').val(ret.data.id)
                    }else{
                        if(ret.msg) Toastr.error(ret.msg);
                    }
                },
            });

        }else{
            setInvoiceText('');
        }
    }
    // 删除发票信息
    function delInvoice(id,obj){
        confirm({content:'您确定要删除该发票信息吗？',yes:function(index){
                $.post('/addons/mall/invoice/del',{ids:id},function(data,textStatus){
                    var json = toJson(data);
                    if(json.status==1){
                        layer.msg(json.msg,{icon:1});
                        $(obj).parent().parent().remove();
                        $('#c-invoiceId').val(0);
                        // 选中 `个人`
                        $('.inv_li:first').click();
                    }else{
                        layer.msg(json.msg,{icon:2});
                    }
                });
            }});
    }

    /**使用积分支付
     *
     * @param v
     */
    function checkScoreBox(v){
        if(v){
            var val = $('#c-isUseScore').attr('dataval');
            $('#c-useScore').val(val);
            $('#c-scoreMoney').show();
        }else{
            $('#c-scoreMoney').hide();
        }
        getOrderMoney();
    }

    /**
     * 提交订单
     */
    function addOrder(){
        var params = {};
        params.deliverType = $('#c-deliverType').val();
        params.s_addressId = $('#c-s_addressId').val();
        params.payType = $('#c-payType').val();

        params.isUseScore = $('#c-isUseScore').prop('checked')?1:0;
        params.useScore = $('#c-useScore').val();

        //组装店铺留言为数组
        var remarkShop = [], remarkShopId = [], remarkArray = [];
        $('input[name="row[remarkshop]"]').each(function () {
            remarkShop.push($(this).val());
        });
        $('input[name="row[remarkshop]"]').each(function () {
            remarkShopId.push($(this).data("shop-id"));
        });
        if(remarkShop.length>1 && remarkShop.length===remarkShopId.length){
            remarkShop.forEach(function (item,index) {
                remarkArray[remarkShopId[index]] = item;
            })
        }else{
            remarkArray[remarkShopId] = remarkShop
        }
        params.memo = remarkArray;
        params.isInvoice = $('#c-isInvoice').val();
        params.invoiceClient = $('#c-invoiceClient').val();
        console.log(params);
        $.ajax({
            url: '/addons/mall/order/add',
            type: 'post',
            dataType: 'json',
            data: params,
            success: function (ret) {
                if(ret.code){
                    if(ret.msg) Toastr.success(ret.msg);
                    location.href='/addons/mall/order/onlinePayCode/orderNo/'+ret.data;
                }else{
                    if(ret.msg) Toastr.error(ret.msg);
                }
            },
        });
    }

</script>
{/block}

